package com.sbeam.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sbeam.mapper.FactoryMapper;
import com.sbeam.mapper.GamesMapper;
import com.sbeam.mapper.SortMapper;
import com.sbeam.mapper.UserMapper;
import com.sbeam.pojo.Factory;
import com.sbeam.pojo.Games;
import com.sbeam.pojo.Sort;
import com.sbeam.pojo.User;
import com.sbeam.vo.Game;
import com.sbeam.vo.GameVO;
import com.sbeam.vo.PageResult;
import com.sbeam.vo.SimilarGameVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

@Service
public class GamesServiceImpl implements GamesService{

    @Autowired
    private GamesMapper gamesMapper;

    @Autowired
    private FactoryMapper factoryMapper;

    @Override
    public List<Games> getGamesList() {
        List<Games> list = gamesMapper.getGamesListM();
        for (Games games:list){
            int id = games.getFactoryId();
            Factory factory = factoryMapper.getFactoryById(id);
            games.setFactory(factory);
            games.setPrice(Double.valueOf(games.getPrice()/100));
        }
        return list;
    }

    @Override
    public int updateGamesStatus(Games games) {
        games.setUpdated(new Date());
        return gamesMapper.updateGamesStatus(games);
    }

    @Override
    public PageResult searchByName(PageResult pageResult) {
        String searchKey = pageResult.getQuery();
        Integer searchId = pageResult.getId();
        if (searchKey==null || "null".equals(searchKey)){
            searchKey="";
        }
        Map map = new HashMap();
        map.put("key","%"+searchKey+"%");
        map.put("start",(pageResult.getPageNum()-1)* pageResult.getPageSize());
        map.put("pageSize",pageResult.getPageSize());
        if (searchId == 1){
            List<Games> list = gamesMapper.findGamesByName(map);
            for (Games game:list){
                game.setPrice(game.getPrice()/100);
                Integer factoryId=game.getFactoryId();
                Factory factory = factoryMapper.getFactoryById(factoryId);
                game.setFactory(factory);
            }
            pageResult.setRows(list);
        }else if (searchId == 2){
            List<Factory> list = factoryMapper.findFactoryByName(map);
            List<Games> gamesList = new ArrayList<>();
            for (Factory factory:list){
                Integer factoryId = factory.getId();
                List<Games> games = gamesMapper.getGamesByFactoryId(factoryId);
                for (Games game:games){
                    game.setPrice(game.getPrice()/100);
                    game.setFactory(factory);
                }
                gamesList.addAll(games);
            }
            pageResult.setRows(gamesList);
        }
        return pageResult;
    }

    @Override
    public Games getGamesById(Integer id) {
        Games games = gamesMapper.getGamesById(id);
        games.setPrice(games.getPrice()/100);
        return games;
    }

    @Override
    public int updateGamesById(Games games) {
        games.setUpdated(new Date());
        games.setPrice(games.getPrice()*100);
        return gamesMapper.updateGamesById(games);
    }

    @Override
    public int deleteGamesById(Integer id) {
        return gamesMapper.deleteGamesById(id);
    }

    @Override
    public int addGames(Games games) {
        games.setDiscount(100)
                .setStatus(true)
                .setPrice(games.getPrice()*100)
                .setCreated(new Date())
                .setUpdated(new Date());
        return gamesMapper.addGames(games);
    }

    @Autowired
    private SortMapper sortMapper;

    private String serviceURL = "http://localhost:8888/images";

    @Autowired
    private UserMapper userMapper;

    @Override
    public GameVO getGameModel(Integer id,String username) {
        //1.获取games表
        Games games = gamesMapper.getGamesById(id);
        if (games==null) {
            return null;
        }
        //2.将games表的内容赋值给game表
        Game game = new Game();
        game.setId(games.getId())
                .setName(games.getName())
                .setParentId(games.getParentId())
                .setPrice(games.getPrice()/100)
                .setDiscount(games.getDiscount())
                .setDetails(games.getDetails())
                .setFactoryId(games.getFactoryId())
                .setStatus(games.getStatus())
                .setCreated(games.getCreated())
                .setUpdated(games.getUpdated());

        //3.对其中的images进行处理，将其转化为List集合
        if (games.getImages()!=null&&!games.getImages().equals("")) {
            String[] images = games.getImages().split(",");
            List<String> list = new ArrayList<>();
            for (String image : images) {
                String concat = serviceURL.concat(image);
                list.add(concat);
            }
            game.setImages(list);
        }

        //4.根据game表的值去查厂商信息
        Factory factory = factoryMapper.getFactoryById(game.getFactoryId());

        //5.根据game表的值去查分类信息
        Sort sort = sortMapper.getSortById(game.getParentId());

        //6.根据分类信息查询同类游戏
        SimilarGameVO similarGameVO = new SimilarGameVO();
        List<String> images = new ArrayList<>();
        List<Integer> gameIds = new ArrayList<>();
        List<Games> gamesByParentId = gamesMapper.findGamesByParentId(game.getParentId());
        for (int i = 0; i < gamesByParentId.size(); i++) {
            if (images.size()>=5){
                break;
            }
            Games similarGame = gamesByParentId.get(i);
            if (similarGame.getImages()!=null&&!"".equals(similarGame.getImages())) {
                String oldImage = similarGame.getImages();
                int index = oldImage.indexOf(",");
                String newImage = oldImage.substring(0, index);
                String concat = serviceURL.concat(newImage);
                images.add(concat);
                gameIds.add(similarGame.getId());
            }
        }
        similarGameVO.setGameIds(gameIds).setImages(images);

        //6.查看是否已购买此游戏
        User user = userMapper.getUserInfo(username);
        Integer hasBuyThisGames = 0;
        if (user.getOrdergame()!=null&&!user.getOrdergame().equals("")){
            List<String> orderGames = new ArrayList<>(Arrays.asList(user.getOrdergame().split(",")));
            for (String aGameId : orderGames){
                //由于Integer超过了-128~127的常量池，此处只能用equals进行比较
                if (aGameId.replace(" ","").equals(String.valueOf(game.getId()))){
                    hasBuyThisGames=1;
                    break;
                }
            }
        }

        //7.将数据封装并返回
        GameVO gameModel = new GameVO(game,factory,sort,similarGameVO,hasBuyThisGames);

        return gameModel;
    }

    /* 分页查询
     * 语法:selectPage语法说明
     *      1.page: MP内部指定的分页对象
     *      2.queryWrapper 条件构造器
     *      Sql: where title like "%xxx%"
     * @param pageResult   【列表页面展示的字段(5个)与pageResult对象(5个)属性映射】
     * @return
     */
    @Override
    public PageResult getGamesList(PageResult pageResult) {
        //判断数据是否有值
        QueryWrapper<Games> queryWrapper = new QueryWrapper<>();
        //如果查询条件有值，返回true；无值返回false
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        //flag为true，按查询条件执行；false则查询所有数据
        queryWrapper.like(flag, "name",pageResult.getQuery());
        //编辑MP的分页对象   四个属性有用（页数/条数/总数/记录）   传递=页数/条数
        //创建page对象，并传入当前页数与每页条数，利用MP提供的工具API进行页面封装
        IPage<Games> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        //调用MP的selectPage方法，传入相应参数，获取封装好的page对象
        page = gamesMapper.selectPage(page, queryWrapper);
        //获取总数
        long total = page.getTotal();
        //获取记录数
        List<Games> rows = page.getRecords();
        //将数据封装到pageResult对象中
        //为什么要将total、rows封装？？ 原因：因为返回值类型的对象pageResult中包含5个属性，
        // 其中三个由URL传过来，剩余2个需要自己手动添加，才能构成一个完整的pageResult对象返回
        return pageResult.setTotal(total).setRows(rows);
    }

}
